#include"bmp.h"

int main(int argc, char const *argv[])
{
    //初始化lcd
    int lcd = open("/dev/fb0", O_RDWR);
    struct fb_var_screeninfo vinfo;
    ioctl(lcd, FBIOGET_VSCREENINFO, &vinfo);
    int lcd_w = vinfo.xres;
    int lcd_h = vinfo.yres;
    int bpp   = vinfo.bits_per_pixel;
    int screen_size = lcd_w * lcd_h * bpp/8;
    char *fb_mem = mmap(NULL, screen_size, PROT_WRITE, MAP_SHARED, lcd, 0);

    //打开BMP图片，获取格式头
    FILE *fp = fopen(argv[1], "r");
    struct bitmap_header head;
    struct bitmap_info info;
    fread(&head, sizeof(head), 1, fp);
    fread(&info, sizeof(info), 1, fp);
    if(info.compression){
        struct rgb_quad quad;
        fread(&quad, sizeof(quad), 1, fp);
    }
    printf("%d * %d [%d]\n", info.width, info.height, head.size);

    //将RGB中的数据读出来
    printf("head.size: %d\n", head.size);
    printf("info.size: %d\n", info.size);
    int rgb_size = head.size - sizeof(head) - sizeof(info);
    char *rgb_data = malloc(rgb_size);
    fread(rgb_data, rgb_size, 1, fp);

    // 计算BMP一行的真实大小
    int pad = ( 4-(info.width*3)%4 ) % 4; // 每一行末尾填充的无效字节，用来保证一行字节数是4的倍数
    int bmp_line_size = info.width * 3 + pad;

    // 4. 妥当地显示图片
    for(int j=0; j<info.height && j<lcd_h; j++)
    {
        // 每一行的偏移量
        int lcd_offset = 800*4*j;
        // 让rgb从RGB数据的最后一行开始
        int rgb_offset = bmp_line_size * (info.height-j-1);
        // 将图片的第一行显示出来
        for (int i = 0; i < lcd_w && i < info.width; i++)
            memcpy(fb_mem+4*i + lcd_offset,
                   rgb_data+3*i + rgb_offset, 3); // 显示下一个像素点
    }

    // 5. 释放资源
    free(rgb_data);
    munmap(fb_mem, screen_size);
    close(lcd);
    return 0;
}
